document.addEventListener("DOMContentLoaded", function() {
    // 获取用户ID
    getUserID().then(userId => {
        if (userId === "not_logged_in") {
            alert('用户未登录');
            window.location.href = '/index.html'; // 重定向到登录页面
        } else {
            fetchUserInfo(userId);
            fetchShippingAddresses(userId); // 获取收货地址列表
        }
    });

    function fetchUserInfo(userId) {
        fetch(`/api/users/get-user-info?userId=${userId}`, {
            credentials: 'include'
        })
            .then(response => response.json())
            .then(data => {
                const userInfoDiv = document.getElementById("user-info");
                userInfoDiv.innerHTML = `
                    <h2>个人信息</h2>
                    <p>Email: ${data.email}</p>
                    <p>姓名: ${data.name}</p>
                    <p>联系方式: ${data.contactInfo}</p>
                    <button onclick="toggleEditUserInfoForm()">编辑个人信息</button>
                `;
                // 创建新建收货地址的按钮，并为其添加点击事件监听器
                const newAddressButton = document.createElement('button');
                newAddressButton.textContent = '新建收货地址';
                newAddressButton.id = 'newAddressButton';
                newAddressButton.addEventListener("click", toggleNewAddressForm); // 添加点击事件监听器
                userInfoDiv.appendChild(newAddressButton);
            })
            .catch(error => {
                console.error('Error fetching user info:', error);
                document.getElementById("user-info").textContent = "获取个人信息失败。";
            });
    }

    window.toggleEditUserInfoForm = function () {
        const editUserInfoForm = document.getElementById("edit-user-info-form");
        if (editUserInfoForm) {
            // 如果表单已存在，仅切换其显示状态
            editUserInfoForm.style.display = editUserInfoForm.style.display === 'none' ? 'block' : 'none';
        } else {
            // 创建表单并插入到页面中
            const formHtml = `
                <form id="edit-user-info-form" style="display:none; margin-top:20px;">
                    <h3>编辑个人信息</h3>
                    <label for="email">Email:</label>
                    <input type="email" id="email" name="email" required><br><br>
                    <label for="name">姓名:</label>
                    <input type="text" id="name" name="name" required><br><br>
                    <label for="contactInfo">联系方式:</label>
                    <input type="text" id="contactInfo" name="contactInfo" required><br><br>
                    <button type="button" onclick="saveEditedUserInfo()">保存</button>
                    <button type="button" onclick="toggleEditUserInfoForm()">取消</button>
                </form>
            `;
            document.body.insertAdjacentHTML('beforeend', formHtml);
            // 填充表单字段
            const email = document.getElementById("email");
            const name = document.getElementById("name");
            const contactInfo = document.getElementById("contactInfo");
            getUserID().then(userId => {
                fetchUserInfoFillForm(userId);
            });
        }
    };

    function fetchUserInfoFillForm(userId) {
        fetch(`/api/users/get-user-info?userId=${userId}`, {
            credentials: 'include'
        })
            .then(response => response.json())
            .then(data => {
                document.getElementById("email").value = data.email;
                document.getElementById("name").value = data.name;
                document.getElementById("contactInfo").value = data.contactInfo;
            })
            .catch(error => {
                console.error('Error fetching user info to fill form:', error);
            });
    }

    window.saveEditedUserInfo = function() {
        getUserID().then(userId => {
            if (userId === "not_logged_in") {
                alert('用户未登录');
                return; // 如果用户未登录，则不执行后续操作
            }

            const email = document.getElementById("email").value;
            const name = document.getElementById("name").value;
            const contactInfo = document.getElementById("contactInfo").value;

            // 发送更新请求
            fetch(`/api/users/update-user-info/${userId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    email: email,
                    name: name,
                    contactInfo: contactInfo
                }),
                credentials: 'include'
            })
                .then(response => {
                    if (response.ok) {
                        alert('个人信息更新成功');
                        fetchUserInfo(userId); // 重新加载用户信息
                        toggleEditUserInfoForm(); // 隐藏表单
                    } else {
                        alert('个人信息更新失败');
                    }
                })
                .catch(error => {
                    console.error('Error updating user info:', error);
                    alert('更新个人信息时出错');
                });
        });
    };

    window.toggleNewAddressForm=function () {
        const newAddressForm = document.getElementById("new-address-form");
        if (newAddressForm) {
            // 如果表单已存在，仅切换其显示状态
            newAddressForm.style.display = newAddressForm.style.display === 'none' ? 'block' : 'none';
        } else {
            // 创建表单并插入到 userInfoDiv 之后
            const formHtml = `
                <form id="new-address-form" style="display:none; margin-top:20px;">
                    <h3>新建收货地址</h3>
                    <label for="recipientName">收货人姓名:</label>
                    <input type="text" id="recipientName" name="recipientName" required><br><br>
                    <label for="phone">电话:</label>
                    <input type="text" id="phone" name="phone" required><br><br>
                    <label for="address">地址:</label>
                    <input type="text" id="address" name="address" required><br><br>
                    <button type="button" onclick="saveNewAddress()">保存地址</button>
                    <button type="button" onclick="toggleNewAddressForm()">取消</button>
                </form>
            `;
            // 插入表单到 userInfoDiv 之后
            document.getElementById("user-info").insertAdjacentHTML('afterend', formHtml);
        }
    }

    window.saveNewAddress = function() {
        getUserID().then(userId => {
            if (userId === "not_logged_in") {
                alert('用户未登录');
                return; // 如果用户未登录，则不执行后续操作
            }

            const recipientName = document.getElementById("recipientName").value;
            const phone = document.getElementById("phone").value;
            const address = document.getElementById("address").value;

            getUserById(userId).then(user => {
                const shippingAddress = {
                    recipientName: recipientName,
                    phone: phone,
                    address: address,
                    user: user // 设置关联的用户
                };

                // 发送 POST 请求以新建地址
                fetch(`/api/shipping-addresses`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(shippingAddress), // 传递整个 shippingAddress 对象
                    credentials: 'include'
                })
                    .then(response => {
                        if (response.ok) {
                            alert('地址保存成功');
                            fetchShippingAddresses(userId);
                            toggleNewAddressForm(); // 隐藏表单
                        } else {
                            alert('地址保存失败');
                        }
                    })
                    .catch(error => {
                        console.error('Error saving address:', error);
                        alert('保存地址时出错');
                    });
            });
        });
    };

    window.deleteAddress = function(addressId) {
        getUserID().then(userId => {
            if (userId === "not_logged_in") {
                alert('用户未登录');
                return; // 如果用户未登录，则不执行后续操作
            }

            // 发送 DELETE 请求以删除地址
            fetch(`/api/shipping-addresses/${addressId}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'include'
            })
                .then(response => {
                    if (response.ok) {
                        alert('地址删除成功');
                        fetchShippingAddresses(userId);
                    } else {
                        alert('地址删除失败');
                    }
                })
                .catch(error => {
                    console.error('Error deleting address:', error);
                    alert('删除地址时出错');
                });
        });
    };

    function fetchShippingAddresses(userId) {
        fetch(`/api/shipping-addresses/user/${userId}`, {
            credentials: 'include'
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                const addressesDiv = document.getElementById("addresses");
                if (data && data.length > 0) {
                    addressesDiv.innerHTML = data.map(address => `
                    <div>
                        <p>${address.recipientName}, ${address.phone}, ${address.address}</p>
                        <button onclick="editAddress(${address.id})">编辑</button>
                        <button onclick="deleteAddress(${address.id})">删除</button>
                    </div>
                `).join('');
                } else {
                    addressesDiv.innerHTML = "<p>暂无收货地址</p>"; // 显示“暂无收货地址”
                }
            })
            .catch(error => {
                console.error('Error fetching addresses:', error);
                document.getElementById("addresses").textContent = "获取收货地址失败：" + error.message;
            });
    }

    function createEditAddressForm() {
        const editAddressForm = document.getElementById("edit-address-form");
        if (!editAddressForm) {
            const formHtml = `
            <form id="edit-address-form" style="display:none; margin-top:20px;">
                <h3>编辑收货地址</h3>
                <label for="recipientName">收货人姓名:</label>
                <input type="text" id="recipientName" name="recipientName" required><br><br>
                <label for="phone">电话:</label>
                <input type="text" id="phone" name="phone" required><br><br>
                <label for="address">地址:</label>
                <input type="text" id="address" name="address" required><br><br>
                <input type="hidden" id="addressId" name="addressId"> <!-- 用于存储当前编辑的地址ID -->
                <button type="button" onclick="saveEditedAddress()">保存地址</button>
                <button type="button" onclick="toggleEditAddressForm()">取消</button>
            </form>
        `;
            document.body.insertAdjacentHTML('beforeend', formHtml);
        } else {
            console.log("Edit address form already exists"); // 调试信息
        }
    }

    window.toggleEditAddressForm = function() {
        const editAddressForm = document.getElementById("edit-address-form");
        if (editAddressForm) {
            // 如果表单已存在，仅切换其显示状态
            if (editAddressForm.style.display === 'none') {
                editAddressForm.style.display = 'block'; // 显示表单
            } else {
                editAddressForm.style.display = 'none'; // 隐藏表单
            }
        } else {
            console.error("Edit address form does not exist"); // 调试信息
        }
    }

    window.editAddress = function(addressId) {
        // 确保编辑地址表单存在
        createEditAddressForm();

        // 获取编辑地址表单中的输入字段
        const recipientNameInput = document.getElementById("recipientName");
        const phoneInput = document.getElementById("phone");
        const addressInput = document.getElementById("address");
        const addressIdInput = document.getElementById("addressId");

        // 发送请求获取地址详情
        fetch(`/api/shipping-addresses/${addressId}`, {
            credentials: 'include'
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(address => {
                if (address) {
                    // 填充表单字段
                    console.log("Filling form with address data:", address); // 调试信息
                    recipientNameInput.value = address.recipientName;
                    phoneInput.value = address.phone;
                    addressInput.value = address.address;
                    addressIdInput.value = address.id; // 设置当前编辑的地址ID
                    document.getElementById("edit-address-form").style.display = 'block'; // 显示表单
                } else {
                    console.error("Failed to load address data"); // 调试信息
                    alert('地址加载失败');
                }
            })
            .catch(error => {
                console.error('Error fetching address:', error);
                alert('加载地址时出错');
            });
    };

    window.saveEditedAddress = function() {
        getUserID().then(userId => {
            // 检查用户是否登录
            if (userId === "not_logged_in") {
                alert('用户未登录');
                return; // 如果用户未登录，则不执行后续操作
            }

            // 获取表单数据
            const addressIdElement = document.getElementById("addressId");
            const recipientNameElement = document.getElementById("recipientName");
            const phoneElement = document.getElementById("phone");
            const addressElement = document.getElementById("address");

            // 检查元素是否存在
            if (!addressIdElement || !recipientNameElement || !phoneElement || !addressElement) {
                console.error('Some elements are missing on the page.');
                return;
            }

            const addressId = parseInt(addressIdElement.value, 10); // 转换为整数
            const recipientName = recipientNameElement.value;
            const phone = phoneElement.value;
            const address = addressElement.value;

            // 获取用户信息
            getUserById(userId).then(user => {
                const shippingAddress = {
                    recipientName: recipientName,
                    phone: phone,
                    address: address,
                    user: user // 设置关联的用户
                };

                // 发送更新请求
                fetch(`/api/shipping-addresses/updateaddress/${addressId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(shippingAddress), // 传递整个 shippingAddress 对象
                    credentials: 'include'
                })
                    .then(response => {
                        if (response.ok) {
                            // 地址更新成功
                            alert('地址更新成功');
                            // 刷新当前页面
                            window.location.reload();
                        } else {
                            // 地址更新失败
                            alert('地址更新失败');
                        }
                    })
                    .catch(error => {
                        // 处理错误
                        console.error('Error updating address:', error);
                        alert('更新地址时出错');
                    });
            });
        });
    };

    function getUserID() {
        return fetch('/api/get-user-id', {
            credentials: 'include'
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Failed to fetch user ID');
                }
                return response.text();
            })
            .catch(error => {
                console.error('Error fetching user ID:', error);
                alert('无法获取用户ID');
                return Promise.resolve("not_logged_in");
            });
    }

    function getUserById(userId) {
        return fetch(`/api/users/get-user-info?userId=${userId}`, {
            credentials: 'include'
        })
            .then(response => response.json());
    }
});

